package com.petter.shiro.realm;

import com.petter.core.entry.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * @author : GD
 * @date :2021/8/24 : 16:40
 */
public class UserRealm extends AuthorizingRealm {
    /**
     * 权限认证，即登录过后，每个身份不一定，对应的所能看的页面也不一样。
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 角色
        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        if ("admin".equals(user.getNumber())) {
            roles.add("admin");
            permissions.add("op:write");
        } else {
            roles.add("user");
            permissions.add("op:read");
        }
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 身份认证。即登录通过账号和密码验证登陆人的身份信息。
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String userNumber = (String) token.getPrincipal();
        String password = (String) token.getCredentials();

        if(!"admin".equals(userNumber)){
            throw new AccountException("用户名不正确");
        }
        if("123".equals(password)){
            throw new AccountException("密码不正确");
        }
        return  new SimpleAuthenticationInfo(userNumber, password,getName());
    }
}
